package net.yla.smartbus.core.base;

import net.yla.smartbus.core.api.BaseApi;
import net.yla.smartbus.core.api.RequestCode;
import net.yla.smartbus.core.exception.AppException;
import net.yla.smartbus.core.util.RedisUtil;
import net.yla.smartbus.core.util.Web;
import net.yla.smartbus.module.ba.right.login.dto.UserSession;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * BaseController
 *
 * @author ZengXiaoLiang
 */
public class BaseController extends BaseApi {


    @Autowired
    private RedisUtil redisUtil;
//    @Autowired
//    private LoginService loginService;


    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    public RedisUtil getRedisUtil() {
        return redisUtil;
    }

    public void setRedisUtil(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    /**
     * 查询当前登录的用户
     *
     * @return
     */
    public UserSession getUserSession() {
        // 获取用户标识号
//        String ak = getAK();
        // 接收到请求，记录请求内容
        String token = getToken();
        logger.info("当前登录账户token======================={}", token);
        // 用于测试给最高权限
        if (StringUtils.isEmpty(token)) {
//			throw new AppException("用户未登陆", RequestCode.Not_Login);
//            return loginService.getLoginDTO(3037, 35);
        }

        UserSession dto = (UserSession) redisUtil.get(token);
        if (dto == null) {
            throw new AppException("用户未登陆", RequestCode.Not_Login);
        }
        return dto;
    }

    /**
     * 通过当前线程的请求中各个部分尝试获取当前用户token
     */
    protected String getToken() {
        HttpServletRequest request = Web.getCurrentRequest();

        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("__token")) {
                    return cookie.getValue();
                }
            }
        }

        String token = request.getHeader("__token");
        if (StringUtils.isNotBlank(token)) {
            return token;
        }

        return request.getParameter("__token");
    }

    /**
     * 通过当前线程的请求中各个部分尝试获取当前用户ak
     */
    protected String getAK() {
        HttpServletRequest request = Web.getCurrentRequest();

        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("__ak")) {
                    return cookie.getValue();
                }
            }
        }

        String token = request.getHeader("__ak");
        if (StringUtils.isNotBlank(token)) {
            return token;
        }

        return request.getParameter("__ak");
    }

    /**
     * 从request中获取请求方IP
     *
     * @return
     */
    public String getIpAddress() {
        HttpServletRequest request = Web.getCurrentRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip != null) {
            //对于通过多个代理的情况，最后IP为客户端真实IP,多个IP按照','分割
            int position = ip.indexOf(",");
            if (position > 0) {
                ip = ip.substring(0, position);
            }
        }
        return ip;
    }

    public static String getParameters(HttpServletRequest request) {
        String str = "";
        Map map = request.getParameterMap();
        Set keSet = map.entrySet();
        String value = "";
        for (Iterator itr = keSet.iterator(); itr.hasNext(); ) {
            Map.Entry me = (Map.Entry) itr.next();
            Object ok = me.getKey();
            Object ov = me.getValue();
            if (null == ov) {
                value = "";
            } else if (ov instanceof String[]) {
                String[] values = (String[]) ov;
                for (int i = 0; i < values.length; i++) {
                    value = values[i] + "|";
                }
                value = value.substring(0, value.length() - 1);
            } else {
                value = ov.toString();
            }

            if (!"oper".equals(ok)) {
                str += ok + "=" + value + "&";
            }
        }

        if (str.endsWith("&")) {
            str = str.substring(0, str.length() - 1);
        }
        return str;
    }

    /**
     * 清除当前账号所在公司所有用户的可见用户id缓存
     */
    protected void cleanPossibleVisibleUserCache() {
        //        try {
        //            EmployeeDO emp = this.getCurrentUserToken();
        //            String possibleVisibleUserKey = CacheKeyPrefix.VISIBLE_USERINFO + CacheKeyPrefix.SEPARATOR +
        //                    CacheKeyPrefix.LOGIN_USERINFO + CacheKeyPrefix.SEPARATOR + "*" +
        //                    CacheKeyPrefix.SEPARATOR + emp.getCompanyId();
        //            redisUtil.removePattern(possibleVisibleUserKey);
        //        } catch (Exception e) {
        //            e.printStackTrace();
        //        }
    }

    /**
     * 清除当前账号之前可能存在的token缓存
     */
    protected void cleanPossibleTokenCache() {
        //        try {
        //            EmployeeDO emp = this.getCurrentUserToken();
        //            String possibleToken = CacheKeyPrefix.LOGIN_USERINFO + CacheKeyPrefix.SEPARATOR + "*_" + emp.getId();
        //            redisUtil.removePattern(possibleToken);
        //        } catch (Exception e) {
        //            logger.error(e.getMessage(), e);
        //        }
    }
}
